
import com.artesophy.library.login.Login;

import flash.data.SQLConnection;
import flash.data.SQLResult;
import flash.data.SQLStatement;
import flash.events.MouseEvent;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
import flash.filesystem.File;
import flash.utils.setTimeout;

import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import mx.collections.IList;
import mx.events.StateChangeEvent;

public var loginDB:SQLConnection;
public var loginDBStatement:SQLStatement;
[Bindable] public var loginCollection:ArrayCollection = new ArrayCollection();

private function initLoginDatabase():void
{
	loginDB = new SQLConnection();
	var dbFile:File = File.applicationStorageDirectory.resolvePath("login.db");
	loginDB.open(dbFile);
	loginDBStatement = new SQLStatement();
	loginDBStatement.sqlConnection = loginDB;
	
	loginDBStatement.itemClass = Login;
	loginDBStatement.addEventListener(SQLEvent.RESULT, handleResult);
	//dbStatement.addEventListener(SQLErrorEvent.ERROR, createError);
	
	loginDBStatement.text = "CREATE TABLE IF NOT EXISTS logins ( no INTEGER PRIMARY KEY AUTOINCREMENT, isLogin TEXT, mId TEXT, mPermission TEXT)";
	loginDBStatement.execute();
	
}

private function handleResult(event:SQLEvent):void
{
	var result:SQLResult = loginDBStatement.getResult();
	if (result != null) {  
		loginCollection = new ArrayCollection(result.data);
		try{
			isLogin = loginCollection[0].isLogin;
			mId = loginCollection[0].mId;
			mPermission = loginCollection[0].mPermission;
		}catch(e:Error){}
	}
	trace(loginCollection.toString());
}

private function getLogins():void
{
	loginDBStatement.text = "SELECT * from logins";
	loginDBStatement.execute();
}

private function onSaveLogin():void{
	
	var login:Login = new Login();
	
	delLogin();
	
	login.isLogin = "TRUE";
	login.mId = mId;
	login.mPermission = mPermission;
	
	addLogin(login);
}


private function addLogin(login:Login):void
{
	
	
	try{
		loginDBStatement.text = "INSERT into logins (isLogin,mId,mPermission) values('" +
		login.isLogin + "','" +
		login.mId + "','" +
		login.mPermission + "')";
	}catch(e:Error){trace(e.toString());}
	
	loginDBStatement.execute();
}

private function delLogin():void
{
	var sqlDelete:String = "delete from logins";
	loginDBStatement.text = sqlDelete;
	loginDBStatement.execute();
	getLogins();
}
